<template>
  <el-form ref="postFormRef" label-width="150px" class="ruleForm" :model="postForm" :rules="rules">
    <el-form-item label="实列名称：" prop="name">
      <el-col :span="12">
        <el-input  v-model="postForm.name" maxlength="60" show-word-limit placeholder="请输入实列名称,不能超过60个字符" />
      </el-col>
    </el-form-item>
    <el-form-item label="标签：" prop="tag">
      <el-col :span="12">
        <el-input  v-model="postForm.tag" maxlength="60" show-word-limit placeholder="请输入标签,不能超过60个字符" />
      </el-col>
    </el-form-item>
    <el-form-item label="主办方：" prop="sponsor">
      <el-col :span="12">
        <el-input  v-model="postForm.sponsor"  show-word-limit />
      </el-col>
    </el-form-item>
    <el-form-item label="主办方图像：" prop="thumbnail">
      <el-col :span="12">
        <choose-file tips="建议尺寸200x200像素" :limit="1" v-model="postForm.thumbnail" />
      </el-col>
    </el-form-item>
    <el-form-item label="行业：" prop="industryId">
      <el-col :span="12">
        <example-industry v-model="postForm.industryId" />
      </el-col>
    </el-form-item>
    <el-form-item label="分类：" prop="categoryId">
      <el-col :span="12">
        <example-category v-model="postForm.categoryId" />
      </el-col>
    </el-form-item>
    <el-form-item label="活动时间：" prop="startDate">
      <el-col :span="6">
         <time-range v-model:begin-time="postForm.startDate" v-model:end-time="postForm.endDate" @update:begin-time="postForm.startDate  = $event" @update:end-time="postForm.endDate  = $event" />
      </el-col>
    </el-form-item>
    <el-form-item label="活动目的：" prop="purpose">
      <el-col :span="12">
        <el-input :rows="2" type="textarea"  v-model="postForm.purpose" show-word-limit  />
      </el-col>
    </el-form-item>
    <el-form-item label="客户备注：" prop="remark">
      <el-col :span="12">
        <el-input :rows="2" type="textarea"  v-model="postForm.remark" show-word-limit  />
      </el-col>
    </el-form-item>
    <el-form-item label="参与人员：" prop="attendees">
      <el-col :span="12">
        <el-input  v-model="postForm.attendees" show-word-limit  />
      </el-col>
    </el-form-item>
    <el-form-item label="参与人数：" prop="people">
      <el-col :span="12">
        <el-input-number v-model="postForm.people" :min="0" controls-position="right" />
      </el-col>
    </el-form-item>
    <el-form-item label="场地要求：" prop="requirements">
      <el-col :span="12">
        <el-input  v-model="postForm.requirements" show-word-limit  />
      </el-col>
    </el-form-item>
    <el-form-item label="体验：" prop="experience">
      <el-col :span="12">
        <el-input  v-model="postForm.experience" show-word-limit  />
      </el-col>
    </el-form-item>
    <el-form-item label="选择顾问：" prop="adviserId">
      <el-col :span="12">
        <example-adviser v-model="postForm.adviserId" />
      </el-col>
    </el-form-item>
    <el-form-item label="顾问备注：" prop="adviserRemark">
      <el-col :span="12">
        <el-input :rows="2" type="textarea"  v-model="postForm.adviserRemark" show-word-limit  />
      </el-col>
    </el-form-item>
    <el-form-item label="理由：" prop="reason">
      <el-col :span="12">
        <el-input  :rows="2" type="textarea" v-model="postForm.reason" show-word-limit  />
      </el-col>
    </el-form-item>
    <el-form-item label="现场描述：" prop="description">
      <t-editor v-model="postForm.description" />
    </el-form-item>
    <el-form-item label="特色：" prop="featuresIds">
      <features  :type="PositionType.Case" multiple v-model="postForm.featuresIds" />
    </el-form-item>
    <el-form-item label="场地：" prop="venueId">
      <meeting  v-model="postForm.venueId" />
    </el-form-item>
    <el-form-item label="流程：">
      <el-table :data="postForm.process" style="width: 100%">
        <el-table-column label="名称">
            <template #default="scope">
              <form-item :prop="'process.' + scope.$index + '.name'"  :rules="[{ required: true, message: '请输入名称', trigger: 'blur' }]" >
                <el-input v-model="scope.row.name" :key="scope.$index" placeholder="请输入名称" clearable />
              </form-item>
            </template>
          </el-table-column>
          <el-table-column label="描述">
            <template #default="scope">
              <form-item :prop="'process.' + scope.$index + '.description'"  :rules="[{ required: true, message: '请输入描述', trigger: 'blur' }]" >
                <el-input v-model="scope.row.description" :key="scope.$index" placeholder="请输入描述" clearable />
              </form-item>
            </template>
          </el-table-column>
          <el-table-column label="开始时间">
            <template #default="scope">
              <form-item :prop="'process.' + scope.$index + '.startDate'"  :rules="[{ required: true, message: '请选择开始时间', trigger: 'blur' }]" >
                <el-date-picker class="ml-gutter" value-format="YYYY-MM-DD hh:mm:ss" v-model="scope.row.startDate" type="date" placeholder="请选择开始时间" />
              </form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="right" width="100">
            <template #default="scope">
              <el-button @click="handleProcessDelete(scope.$index)" type="text">删除</el-button>
            </template>
          </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button @click="handleProcessAdd"  class="button-header"  type="primary" :icon="Plus">添加流程</el-button>
    </el-form-item>
    <el-form-item label="图片：" prop="images">
      <choose-file tips="建议尺寸800x800像素" :limit="5" v-model="postForm.images" />
    </el-form-item>
  </el-form>
  <div class="footer">
    <el-button @click="router.push('/case/example')">取消</el-button>
    <el-button type="primary" @click="handleSave(postFormRef)">确定</el-button>
  </div>
</template>
<script lang="ts" setup>
import { Plus } from '@element-plus/icons-vue'
import ChooseFile from '@/components/ChooseFile.vue'
import ExampleIndustry from '@/components/ExampleIndustry.vue'
import ExampleCategory from '@/components/ExampleCategory.vue'
import ExampleAdviser from '@/components/ExampleAdviser.vue'
import TimeRange from '@/components/TimeRange.vue'
import TEditor from '@/components/TEditor.vue'
import Features from '@/components/Features.vue'
import Meeting from '@/components/Meeting.vue'
import { ref, reactive, onMounted } from 'vue'
import { useRoute,useRouter } from 'vue-router'
import { ElMessage, ElForm, ElMessageBox } from 'element-plus'
import { PositionType } from '@/utils/enum'
import {ExampleSave, GetExampleDetails } from '@/api/example'
const router = useRouter()

const postForm =ref<ExampleEdit>({
  id: useRoute().query.id ? Number(useRoute().query.id) : 0,
  name: '',
  tag: '',
  sponsor: '',
  thumbnail: '',
  industryId: undefined,
  categoryId:undefined,
  startDate:undefined,
  endDate:undefined,
  purpose: '',
  remark: '',
  attendees: '',
  people: 0,
  requirements: '',
  experience: '',
  adviserId: undefined,
  adviserRemark: '',
  reason: '',
  venueId: undefined,
  description: '',
  process: [],
  featuresIds: [],
  images: []
})
const rules = reactive({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  tag: [{ required: true, message: '请选择标签', trigger: 'blur' }],
  sponsor: [{ required: true, message: '先输入主办方', trigger: 'blur' }],
  thumbnail: [{ required: true, message: '请选择图像', trigger: 'change' }],
  industryId: [{ required: true, message: '请选择行业', trigger: 'change' }],
  categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  purpose: [{ required: true, message: '请输入活动目的', trigger: 'blur' }],
  remark: [{ required: true, message: '请输入客户备注', trigger: 'blur' }],
  attendees: [{ required: true, message: '请输入参会人员', trigger: 'blur' }],
  people: [{ required: true, message: '请输入人数', trigger: 'blur' }],
  requirements: [{ required: true, message: '请输入场地要求', trigger: 'blur' }],
  experience: [{ required: true, message: '请输入体验', trigger: 'blur' }],
  adviserId: [{ required: true, message: '请选择顾问', trigger: 'change' }],
  adviserRemark: [{ required: true, message: '请输入顾问备注', trigger: 'blur' }],
  reason: [{ required: true, message: '请输入理由', trigger: 'blur' }],
  venueId: [{ required: true, message: '请选择场地', trigger: 'change' }],
  description: [{ required: true, message: '请输入现场内容' }],
  featuresIds: [{ type: 'array', required: true, message: '请选择特色', trigger: 'change' }],
  images: [{ type: 'array', required: true, message: '请上传一张图片', trigger: 'change' }]
})
const dateRange = ref('')
type FormInstance = InstanceType<typeof ElForm>
const postFormRef = ref<FormInstance>()
/**
 * 点击保存
 * @param formEl 
 */
const handleSave = (formEl: FormInstance | undefined): void => {
  if(!formEl)
    return 
  formEl.validate(valid => {
    if(valid) {
      if(postForm.value.process.length === 0) {
        return ElMessage.error('请添加流程')
      }
      try {
        postForm.value.process.forEach((item,index) => {
          if(!item.name)
            throw new Error(`流程${index + 1}名称不能为空`)
          if(!item.description)
            throw new Error(`流程${index + 1}描述不能为空`)
          if(!item.startDate)
            throw new Error(`流程${index + 1}开始时间不能为空`)
        item.sequence = index + 1
      })
      } catch (error:any) {
          return ElMessage.error(error.message)
      }
      ExampleSave(postForm.value).then((res:ServiceResponse<any>) => {
      if (res.success) {
          ElMessage.success('操作成功')
          router.push('/case/example')
        }
      else 
        return ElMessage.error(res.msg)
      })
    }
  })
}

/**
 * 添加流程
 */
const handleProcessAdd = ():void => {
  postForm.value.process.push({
    id: 0,
    exampleId: 0,
    sequence: 0,
    name: '',
    description: '',
    startDate: undefined
  })
}

/**
 * 删除流程
 * @param index 
 */
const handleProcessDelete = (index: number): void => {
    ElMessageBox.confirm('确定要删除吗?', '删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      postForm.value.process.splice(index, 1)
    }).catch(() => {})
}
const loadData = ():void => {
  if(postForm.value.id > 0) {
      GetExampleDetails(postForm.value.id).then((res:ServiceResponse<ExampleEdit>) => {
      if(res.data)
          postForm.value = res.data 
      })
  }
}
onMounted(() => {
  loadData()
})
</script>
<style lang="scss" scoped>
  @import '@/assets/styles/mixin.scss';
  @import '@/assets/styles/tablePage.scss';
  @import '@/assets/styles/formPage.scss';
  
.ruleForm {
  margin-bottom: 50px;
}
</style>